//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package main

import (
	"embed"
	"fmt"
	"io/fs"
	"net/http"
	"strings"

	"atomgit.com/openlinksaas/ssh-proxy/gen_code"
	"github.com/gorilla/handlers"
)

//go:embed proto/index_0.1.2.yml
var apiDefContent string

//go:embed web/dist
var webFs embed.FS

type ApiDef struct {
	host string
}

func (r *ApiDef) Routes() gen_code.Routes {
	return []gen_code.Route{
		{
			Name:    "apiDef",
			Method:  "GET",
			Pattern: "/api.yml",
			HandlerFunc: func(writer http.ResponseWriter, _req *http.Request) {
				h := writer.Header()
				h.Set("Content-Type", "application/yaml;charset:utf-8")
				writer.WriteHeader(200)
				content := strings.Replace(apiDefContent, "url: localhost", fmt.Sprintf("url: http://%s", r.host), 1)
				writer.Write([]byte(content))
			},
		},
	}
}

var fsHandler http.Handler

type Web struct {
}

func (r *Web) ServeHTTP(writer http.ResponseWriter, req *http.Request) {
	if fsHandler == nil {
		newFs, err := fs.Sub(webFs, "web/dist")
		if err != nil {
			writer.WriteHeader(500)
			writer.Write([]byte(err.Error()))
			return
		}
		tmpHandler := http.FileServer(http.FS(newFs))
		tmpHandler = handlers.CORS(handlers.AllowedOrigins([]string{"*"}),
			handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "OPTIONS"}),
			handlers.AllowedHeaders([]string{"*"}))(tmpHandler)
		fsHandler = tmpHandler
	}
	fsHandler.ServeHTTP(writer, req)
}
